package cn.yuanqiao.archive.archiveFormSave.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.archiveFormSave.domain.YqdaArchiveForm;
import cn.yuanqiao.archive.archiveFormSave.mapper.YqdaArchiveFormMapper;
import cn.yuanqiao.archive.archiveFormSave.service.IYqdaArchiveFormService;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.apache.commons.compress.archivers.ArchiveException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 归档申请单Service业务层处理
 *
 * @author yuanqiao
 * @date 2023-07-26
 */
@Service
public class YqdaArchiveFormServiceImpl implements IYqdaArchiveFormService
{
    @Autowired
    private YqdaArchiveFormMapper yqdaArchiveFormMapper;

    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private ITenantSysDictTypeService sysDictTypeService;
    /**
     * 查询归档申请单
     *
     * @param formId 归档申请单主键
     * @return 归档申请单
     */
    @Override
    public YqdaArchiveForm selectYqdaArchiveFormByFormId(String formId)
    {
        return yqdaArchiveFormMapper.selectYqdaArchiveFormByFormId(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),formId);
    }

    /**
     * 查询归档申请单列表
     *
     * @param yqdaArchiveForm 归档申请单
     * @return 归档申请单
     */
    @Override
    public List<YqdaArchiveForm> selectYqdaArchiveFormList(YqdaArchiveForm yqdaArchiveForm)
    {
        return yqdaArchiveFormMapper.selectYqdaArchiveFormList(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForm);
    }

    /**
     * 新增归档申请单
     *
     * @param yqdaArchiveForm 归档申请单
     * @return 结果
     */
    @Override
    public int insertYqdaArchiveForm(YqdaArchiveForm yqdaArchiveForm)
    {
        return yqdaArchiveFormMapper.insertYqdaArchiveForm(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForm);
    }

    /**
     * 修改归档申请单
     *
     * @param yqdaArchiveForm 归档申请单
     * @return 结果
     */
    @Override
    public int updateYqdaArchiveForm(YqdaArchiveForm yqdaArchiveForm)
    {
        return yqdaArchiveFormMapper.updateYqdaArchiveForm(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForm);
    }

    /**
     * 批量删除归档申请单
     *
     * @param formIds 需要删除的归档申请单主键
     * @return 结果
     */
    @Override
    public int deleteYqdaArchiveFormByFormIds(String[] formIds)
    {
        return yqdaArchiveFormMapper.deleteYqdaArchiveFormByFormIds(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),formIds);
    }

    /**
     * 删除归档申请单信息
     *
     * @param formId 归档申请单主键
     * @return 结果
     */
    @Override
    public int deleteYqdaArchiveFormByFormId(String formId)
    {
        return yqdaArchiveFormMapper.deleteYqdaArchiveFormByFormId(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),formId);
    }

    @Override
    public int batchInsertYqdaArchiveForm(List<YqdaArchiveForm> yqdaArchiveForms) {
        return yqdaArchiveFormMapper.batchInsertYqdaArchiveForm(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForms);
    }

    @Override
    public List<Map<String, Object>> getArchiveInfo(YqdaArchiveForm yqdaArchiveForm, String commonCloumns, String level) throws ArchiveException {
        commonCloumns = "*,";//FIXME 警告：测试用，正式环境需要删除此代码
        //String daType = yqdaArchiveForm.getDaType().toUpperCase();
        Long categoryId = yqdaArchiveForm.getCategoryId();
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        String daType = null;
        if ("jian".equals(level.toLowerCase())){
            daType = "f";
            tableName = tenantCategory.getFileTableName();
        }else if ("juan".equals(level.toLowerCase())){
            daType = "v";
            tableName = tenantCategory.getFolderTableName();
        }else if ("xiangmu".equals(level.toLowerCase())){
            daType = "x";
            tableName = tenantCategory.getItemTableName();
        }else if ("efile".equals(level.toLowerCase())){
            daType = "e";
            tableName = tenantCategory.getEfileTableName();
        }
        /*if (type ==0 &&){

        }else if (type ==1){

        }else if (type ==3){

        }*/

        if ((type ==0&&"jian".equals(level.toLowerCase()))||(type ==1&&"juan".equals(level.toLowerCase()))||(type ==3&&"xiangmu".equals(level.toLowerCase()))){
            sqlBulider.append("SELECT '").append(daType).append("' AS DA_TYPE, ").append(commonCloumns).append(categoryId).append(" AS CATEGORY_ID,'").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName)
                    .append(" WHERE ID IN(").append(yqdaArchiveForm.getArchiveId()).append(") AND IS_DEL = 0");
        }else if ((type ==1&&"jian".equals(level.toLowerCase()))||(type ==3&&"jian".equals(level.toLowerCase()))){
            sqlBulider.append(" SELECT '").append(daType).append("' AS DA_TYPE, ").append(commonCloumns).append(categoryId).append(" AS CATEGORY_ID,'").append(tableName).append("' AS SUB_TABLE_NAME  FROM ").append(tableName)
                    .append("  WHERE ID IN( SELECT DA_ID FROM ").append(tenantCode).append("_YQDA_FOLDER WHERE FOLDER_ID =")
                    .append(yqdaArchiveForm.getArchiveId()).append(") AND IS_DEL = 0");
        }else if (type ==3&&"juan".equals(level.toLowerCase())){
            sqlBulider.append(" SELECT '").append(daType).append("' AS DA_TYPE, ").append(commonCloumns).append(categoryId).append(" AS CATEGORY_ID,'").append(tableName).append("' AS SUB_TABLE_NAME  FROM  ").append(tableName)
                    .append("  WHERE ID IN(SELECT FOLDER_ID FROM ").append(tenantCode).append("_ITEM_FOLDER WHERE ITEM_ID =").append(yqdaArchiveForm.getArchiveId()).append(") AND IS_DEL = 0");
        }else {
            throw new ArchiveException("档案类型daType不能为空");
        }

        return yqdaArchiveFormMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public String getCommonColumns() {
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantFields tenantField = new TenantFields();
        tenantField.setIsCommon("1");
        tenantField.setState("1");
        List<TenantFields> tenantFields = tenantFieldsMapper.selectTenantFieldsList(tenantField);
        StringBuilder fieldCommon = new StringBuilder();
        Set<String> yqdaFields = new HashSet<>();
        Set<String> yqfolderFields = new HashSet<>();
        for (TenantFields item : tenantFields) {
            if ("0".equals(item.getType())) {
                yqdaFields.add(item.getFieldName());
            } else if ("1".equals(item.getType())) {
                yqfolderFields.add(item.getFieldName());
            }
        }
        Set<String> commonFields = new HashSet<>(yqdaFields);
        commonFields.retainAll(yqfolderFields);
        for (String element : commonFields) {
            fieldCommon.append(element).append(",");
        }
        return fieldCommon.toString();
    }

    @Override
    public List<Map<String, Object>> getArchiveListByArchiveForm(YqdaArchiveForm yqdaArchiveForm) {
        yqdaArchiveForm.setState("0");
        yqdaArchiveForm.setUserId(String.valueOf(SecurityUtils.getUserId()));
        List<YqdaArchiveForm> yqdaArchiveForms = selectYqdaArchiveFormList(yqdaArchiveForm);
        if (yqdaArchiveForms.size()==0){
            return null;
        }
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantFields tenantField = new TenantFields();
        tenantField.setIsCommon("1");
        tenantField.setState("1");
        List<TenantFields> tenantFields = tenantFieldsMapper.selectTenantFieldsList(tenantField);
        StringBuilder fieldCommon = new StringBuilder();
        Set<String> yqdaFields = new HashSet<>();
        Set<String> yqfolderFields = new HashSet<>();
        Set<String> yqItemFields = new HashSet<>();
        for (TenantFields item : tenantFields) {
            if ("0".equals(item.getType())) {
                yqdaFields.add(item.getFieldName());
            } else if ("1".equals(item.getType())) {
                yqfolderFields.add(item.getFieldName());
            }else if("3".equals(item.getType())){
                yqItemFields.add(item.getFieldName());
            }
        }
        Set<String> commonFields = new HashSet<>(yqdaFields);
        commonFields.retainAll(yqfolderFields);
        commonFields.retainAll(yqItemFields);
        for (String element : commonFields) {
            fieldCommon.append(element).append(",");
        }
        StringBuilder archiveIdBuilder = new StringBuilder();
        yqdaArchiveForms.forEach(item->archiveIdBuilder.append(item.getArchiveId()).append(","));
        archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
        String archiveIds = archiveIdBuilder.toString();
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        //FIXME 测试用，记得删除
        fieldCommon = new StringBuilder();
        fieldCommon.append("*,");

        sqlBulider.append("SELECT ").append(fieldCommon).append("'f' AS DA_TYPE,DA_ID AS ID,TITLE FROM ").append(tenantCode)
                .append("_YQDA WHERE DA_ID IN(").append(archiveIds).append(") UNION ALL SELECT ").append(fieldCommon)
                .append("'v' AS DA_TYPE,FOLDER_ID AS ID,TITLE FROM ").append(tenantCode).append("_YQFOLDER  WHERE FOLDER_ID IN(").append(archiveIds)
                .append(")  AND IS_DEL = 0 UNION ALL SELECT ").append(fieldCommon)
                .append("'x' AS DA_TYPE,ITEM_ID AS ID,XMMC AS TITLE FROM ").append(tenantCode)
                .append("_YQITEM  WHERE ITEM_ID IN(").append(archiveIds).append(")  AND IS_DEL = 0;");
        return yqdaArchiveFormMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public List<Map<String, Object>> getArchiveListByArchiveCategory(YqdaArchiveForm yqdaArchiveForm) {
        yqdaArchiveForm.setState("0");
        yqdaArchiveForm.setUserId(String.valueOf(SecurityUtils.getUserId()));
        List<YqdaArchiveForm> yqdaArchiveForms = selectYqdaArchiveFormList(yqdaArchiveForm);
        if (yqdaArchiveForms.size()==0){
            return null;
        }
        YqdaArchiveForm tempData = yqdaArchiveForms.get(0);
        Long categoryId = Long.valueOf(tempData.getCategoryIdaf());
        String daType = tempData.getDaType().toUpperCase();
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        if (type==0){
            tableName = tenantCategory.getFileTableName();
        }else if (type==1){
            tableName = tenantCategory.getFolderTableName();
        }else if (type==3){
            tableName = tenantCategory.getItemTableName();
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        StringBuilder archiveIdBuilder = new StringBuilder();
        yqdaArchiveForms.forEach(item->archiveIdBuilder.append(item.getArchiveId()).append(","));
        //FIXME 测试用字段
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));
        //fieldCommon.append("*,");
        tenantMdataLists.forEach(item->{
            if ("F".equals(daType)&&item.getType().equals(0)){
                fieldCommon.append(item.getFieldName()).append(",");
            }else if ("V".equals(daType)&&item.getType().equals(1)){
                fieldCommon.append(item.getFieldName()).append(",");
            }else if ("X".equals(daType)&&item.getType().equals(3)){
                fieldCommon.append(item.getFieldName()).append(",");
            }
        });


        archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
        String archiveIds = archiveIdBuilder.toString();
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        sqlBulider.append("SELECT ID,").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(archiveIds).append(") AND IS_DEL = 0");
        return yqdaArchiveFormMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public List<Map<String, Object>> getArchiveListByCategoryAndIds(String[] archiveIds,Long categoryId,String daType) {

        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        //Integer type = tenantCategory.getType();
        String tableName = null;
        if ("F".equals(daType)){
            tableName = tenantCategory.getFileTableName();
        }else if ("V".equals(daType)){
            tableName = tenantCategory.getFolderTableName();
        }else if ("X".equals(daType)){
            tableName = tenantCategory.getItemTableName();
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        StringBuilder archiveIdBuilder = new StringBuilder();
        //FIXME 测试用字段
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));
        //fieldCommon.append("*,");
        tenantMdataLists.forEach(item->{
            if ("F".equals(daType)&&item.getType().equals(0)){
                fieldCommon.append(item.getFieldName()).append(",");
            }else if ("V".equals(daType)&&item.getType().equals(1)){
                fieldCommon.append(item.getFieldName()).append(",");
            }else if ("X".equals(daType)&&item.getType().equals(3)){
                fieldCommon.append(item.getFieldName()).append(",");
            }
        });


        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        sqlBulider.append("SELECT ID,").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(StringUtils.join(archiveIds,",")).append(") AND IS_DEL = 0");
        return yqdaArchiveFormMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public Map<String, Object> getArchiveSaveDownloadTitle(Long categoryId, Long[] archiveIds, String daType) {

        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        if (type==0){
            tableName = tenantCategory.getFileTableName();
        }else if (type==1){
            tableName = tenantCategory.getFolderTableName();
        }else if (type==3){
            tableName = tenantCategory.getItemTableName();
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        StringBuilder archiveIdBuilder = new StringBuilder();
        List<Map<String,Object>> list = new ArrayList<>();
        List<String> jdList=new ArrayList();
        Map<String,Object> map = new HashMap<>();
        tenantMdataLists.forEach(item->{
            if (item.getType().equals(type)&&item.getIsExport().equals(1)){
                if("1".equals(item.getFieldType().toString())||"4".equals(item.getFieldType().toString())||"7".equals(item.getFieldType().toString())){
                    fieldCommon.append("to_char("+item.getFieldName()+") AS \""+item.getFieldName()+"\"").append(",");
                }else {
                    fieldCommon.append(item.getFieldName()).append(",");
                }
                map.put(item.getFieldName(),item.getFieldCaption());

                list.add(map);

                if("5".equals(item.getShowType().toString())){
                    jdList.add(item.getFieldName());
                }
            }
        });
        /*yqdaArchiveForms.forEach(item->archiveIdBuilder.append(item.getArchiveId()).append(","));
        //FIXME 测试用字段
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));
        fieldCommon.append("*,");


        archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
        String archiveIds = archiveIdBuilder.toString();*/
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        StringBuilder ids = new StringBuilder();
        Arrays.asList(archiveIds).forEach(item->ids.append(item).append(","));
        ids.deleteCharAt(ids.length()-1);
        sqlBulider.append("SELECT ").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(ids).append(") AND IS_DEL = 0");
        List<Map<String, Object>> mapList = yqdaArchiveFormMapper.selectYqdaArchiveList(sqlBulider.toString());
        Map<String,Object> resultMap = new HashMap<>();
        for(String str:jdList){
          for(int j=0;j<mapList.size();j++){
              Map <String, Object>map1=mapList.get(j);
              Set<String> keySet = map1.keySet();
              // 遍历keySet，并输出key的值
              for(String key : keySet){
                 if(key.equals(str.toUpperCase())){
                    //获取字典
                     String value=getDictVal(str,map1.get(key));
                     map1.put(key,value);
                     mapList.set(j,map1);

                 }
              }
          }
        }

        resultMap.put("data",mapList);
        resultMap.put("title",map);
        return resultMap;
    }

    @Override
    public boolean checkArchiveIsAddForm(List<YqdaArchiveForm> yqdaArchiveForms) {
        int i = yqdaArchiveFormMapper.checkArchiveIsAddForm( SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForms);
        return i==0?false:true;
    }

    @Override
    public int updateYqArchiveState(List<YqdaArchiveForm> yqdaArchiveForms, int state) {
        Long categoryId = yqdaArchiveForms.get(0).getCategoryId();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        int i = 0;
        for (YqdaArchiveForm item : yqdaArchiveForms) {
            String archiveId = item.getArchiveId();
            Integer type = tenantCategory.getType();
            if (type == 0){
                String fileTableName = tenantCategory.getFileTableName();
                StringBuilder sqlBulider = new StringBuilder();
                sqlBulider.append("UPDATE ").append(tenantCode).append("_YQDA SET STATE = ").append(state).append(" WHERE DA_ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(fileTableName).append(" SET STATE = ").append(state).append(" WHERE ID = ").append(item.getArchiveId());
                yqdaArchiveFormMapper.updateArchiveBySaveFormArchiveId(sqlBulider.toString());
            }else if (type == 1){
                String fileTableName = tenantCategory.getFileTableName();
                String folderTableName = tenantCategory.getFolderTableName();
                StringBuilder sqlBulider = new StringBuilder();
                sqlBulider.append("UPDATE ").append(tenantCode).append("_YQFOLDER SET STATE = ").append(state).append(" WHERE FOLDER_ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(folderTableName).append(" SET STATE = ").append(state).append(" WHERE ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(tenantCode).append("_YQDA SET STATE = ").append(state).append(" WHERE DA_ID IN (SELECT DA_ID FROM ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID = ").append(item.getArchiveId()).append(")")
                        .append(";UPDATE ").append(fileTableName).append(" SET STATE = ").append(state).append(" WHERE ID IN (SELECT DA_ID FROM ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID = ").append(item.getArchiveId()).append(")");
                yqdaArchiveFormMapper.updateArchiveBySaveFormArchiveId(sqlBulider.toString());
            }else if (type == 3){
                String fileTableName = tenantCategory.getFileTableName();
                String folderTableName = tenantCategory.getFolderTableName();
                String itemTableName = tenantCategory.getItemTableName();
                StringBuilder sqlBulider = new StringBuilder();
                sqlBulider.append("UPDATE ").append(tenantCode).append("_YQITEM SET STATE = ").append(state).append(" WHERE ITEM_ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(itemTableName).append(" SET STATE = ").append(state).append(" WHERE ID = ").append(item.getArchiveId())
                        .append(";UPDATE ").append(tenantCode).append("_YQFOLDER SET STATE = ").append(state).append(" WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM ").append(tenantCode)
                        .append("_ITEM_FOLDER WHERE ITEM_ID = ").append(item.getArchiveId()).append(")")
                        .append(";UPDATE ").append(folderTableName).append(" SET STATE = ").append(state).append(" WHERE ID IN (SELECT FOLDER_ID FROM  ").append(tenantCode)
                        .append("_ITEM_FOLDER WHERE ITEM_ID = ").append(item.getArchiveId()).append(")")
                        .append(";UPDATE ").append(tenantCode).append("_YQDA SET STATE = ").append(state).append(" WHERE DA_ID IN (SELECT DA_ID FROM ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM ").append(tenantCode).append("_ITEM_FOLDER WHERE ITEM_ID = ")
                        .append(item.getArchiveId()).append("))")
                        .append(";UPDATE ").append(fileTableName).append(" SET STATE = ").append(state).append(" WHERE ID IN (SELECT DA_ID FROM  ").append(tenantCode)
                        .append("_YQDA_FOLDER WHERE FOLDER_ID IN (SELECT FOLDER_ID FROM ").append(tenantCode).append("_ITEM_FOLDER WHERE ITEM_ID = ")
                        .append(item.getArchiveId()).append("))");
                yqdaArchiveFormMapper.updateArchiveBySaveFormArchiveId(sqlBulider.toString());
            }

        }
        return i;
    }

    @Override
    public List<YqdaArchiveForm> selectYqdaArchiveFormsByFormIds(String[] formIds) {
        return yqdaArchiveFormMapper.selectYqdaArchiveFormsByFormIds(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),formIds);
    }

    @Override
    public boolean checkArchiveUserCategoryForm(List<YqdaArchiveForm> yqdaArchiveForms) {
        //int i1 = yqdaArchiveFormMapper.checkArchiveUserHaveCategory(yqdaArchiveForms);
        int i = yqdaArchiveFormMapper.checkArchiveUserCategoryForm( SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForms);
        return i==0?false:true;
    }

    @Override
    public List<Map<String, Object>> getArchiveListByArchiveFormList(List<YqdaArchiveForm> yqdaArchiveForms) {

        YqdaArchiveForm tempData = yqdaArchiveForms.get(0);
        Long categoryId = Long.valueOf(tempData.getCategoryIdaf());
        String daType = tempData.getDaType().toUpperCase();
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
        Integer type = tenantCategory.getType();
        String tableName = null;
        if (type==0){
            tableName = tenantCategory.getFileTableName();
        }else if (type==1){
            tableName = tenantCategory.getFolderTableName();
        }else if (type==3){
            tableName = tenantCategory.getItemTableName();
        }

        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setIsHidden(0);
        List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

        StringBuilder fieldCommon = new StringBuilder();
        StringBuilder archiveIdBuilder = new StringBuilder();
        yqdaArchiveForms.forEach(item->archiveIdBuilder.append(item.getArchiveId()).append(","));
        //FIXME 需要解开的注释
        //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));

        archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
        String archiveIds = archiveIdBuilder.toString();
        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        //FIXME 测试流程用数据，字段用* 代替，记得删除
        fieldCommon.append("*,");
        sqlBulider.append("SELECT ").append(fieldCommon).append(categoryId).append(" AS CATEGORY_ID,'").append(daType)
                .append("' AS DA_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(archiveIds).append(") AND IS_DEL = 0");
        return yqdaArchiveFormMapper.selectYqdaArchiveList(sqlBulider.toString());
    }

    @Override
    public int batchUpdateByArchiveIdsAndUserId(YqdaArchiveForm yqdaArchiveForm) {
        return yqdaArchiveFormMapper.batchUpdateByArchiveIdsAndUserId(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForm);
    }

    @Override
    public int batchUpdateByArchiveIds(YqdaArchiveForm yqdaArchiveForm) {
        return yqdaArchiveFormMapper.batchUpdateByArchiveIds(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),yqdaArchiveForm);
    }

    @Override
    public List<YqdaArchiveForm> selectYqdaArchiveFormsByArchiveIds(String[] archiveIds) {
        return yqdaArchiveFormMapper.selectYqdaArchiveFormsByArchiveIds(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),archiveIds,SecurityUtils.getUserId());
    }

    @Override
    public int deleteYqdaArchiveFormByArchiveIdsAndUserId(String[] archiveIds, Long userId) {
        return yqdaArchiveFormMapper.deleteYqdaArchiveFormByArchiveIdsAndUserId(SecurityUtils.getLoginUser().getUser().getTenantCode().toUpperCase(),archiveIds,userId);
    }

    @Override
    public Map<String, Object> getArchiveTotal(String daType,List<String> archiveIds) {
        Map<String,Object> resultMap = new HashMap<>();
        if ("X".equals(daType)){
            resultMap.put("itemTotal",archiveIds.size());
            StringBuilder folderSql = new StringBuilder();
            StringBuilder fileSql = new StringBuilder();
            StringBuilder fileSql2 = new StringBuilder();
            folderSql.append("SELECT COUNT(1) FROM ").append(SecurityUtils.getTenantCode().toUpperCase())
                    .append("_ITEM_FOLDER item INNER JOIN ").append(SecurityUtils.getTenantCode().toUpperCase())
                    .append("_YQFOLDER folder ON item.FOLDER_ID = folder.FOLDER_ID WHERE item.ITEM_ID")
                    .append(" IN(").append(StringUtils.join(archiveIds,",")).append(") AND folder.IS_DEL = 0;");
            fileSql.append("SELECT COUNT(1) FROM ").append(SecurityUtils.getTenantCode().toUpperCase()).
                    append("_YQDA_FOLDER folder INNER JOIN ").append(SecurityUtils.getTenantCode().toUpperCase())
                    .append("_YQDA yqda ON folder.DA_ID = yqda.DA_ID WHERE folder.FOLDER_ID ")
                    .append("IN(").append(StringUtils.join(archiveIds,",")).append(") AND FOLDER_ID IS NULL ")
                    .append("AND yqda.IS_DEL = 0;");
            fileSql2.append("SELECT COUNT(1) FROM ").append(SecurityUtils.getTenantCode().toUpperCase()).
                    append("_YQDA_FOLDER folder INNER JOIN ").append(SecurityUtils.getTenantCode().toUpperCase())
                    .append("_YQDA yqda ON folder.DA_ID = yqda.DA_ID WHERE folder.FOLDER_ID IN(SELECT item.FOLDER_ID FROM ")
                    .append(SecurityUtils.getTenantCode().toUpperCase()).append("_ITEM_FOLDER item INNER JOIN ")
                    .append(SecurityUtils.getTenantCode().toUpperCase()).append("_YQFOLDER folderall ON item.FOLDER_ID ")
                    .append("= folderall.FOLDER_ID AND item.ITEM_ID IN(").append(StringUtils.join(archiveIds,","))
                    .append(")AND folderall.IS_DEL = 0)AND yqda.IS_DEL = 0;");
            Integer folderSize = yqdaArchiveFormMapper.getArchiveTotal(folderSql.toString());
            Integer fileSize = yqdaArchiveFormMapper.getArchiveTotal(fileSql.toString());
            Integer fileSize2 = yqdaArchiveFormMapper.getArchiveTotal(fileSql2.toString());
            resultMap.put("folderTotal",folderSize.intValue());
            resultMap.put("fileTotal",fileSize+fileSize2);
        }else if ("V".equals(daType)){
            resultMap.put("folderTotal",archiveIds.size());
            StringBuilder fileSql = new StringBuilder();
            fileSql.append("SELECT COUNT(1) FROM ").append(SecurityUtils.getTenantCode().toUpperCase())
                    .append("_YQDA_FOLDER folder INNER JOIN ").append(SecurityUtils.getTenantCode().toUpperCase())
                    .append("_YQDA yqda ON folder.da_id = yqda.da_id ").append( "WHERE folder.folder_id IN(")
                    .append(StringUtils.join(archiveIds,",")).append(") AND yqda.is_del = 0;");
            Integer fileSize = yqdaArchiveFormMapper.getArchiveTotal(fileSql.toString());
            resultMap.put("fileTotal",fileSize);
            resultMap.put("itemTotal",0);
        }else if ("F".equals(daType)){
            resultMap.put("fileTotal",archiveIds.size());
            resultMap.put("folderTotal",0);
            resultMap.put("itemTotal",0);
        }else{
            resultMap.put("fileTotal",0);
            resultMap.put("folderTotal",0);
            resultMap.put("itemTotal",0);
        }

        return resultMap;
    }

    public Map<String,List<String>> getIdWhichHasData(String ids,String daType,Long categoryId){
        Map<String, List<String>> map = new HashMap<>();   //项目类型 key:项目id value:案卷ids  案卷类型 key:案卷id value:卷内ids
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory category = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCategory.getTableName());
        String[] idsArr = ids.split(",");
        TenantItemFolder tenantItemFolder = new TenantItemFolder();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        for(int i=0;i<idsArr.length;i++){
            List<String> idsStr = new ArrayList<>();
            String id = idsArr[i];
            Long[] l = {Long.valueOf(id)};
            if("X".equals(daType)){
                Long[] folderIdsByItemIds = folderMapper.getFolderIdsByItemIds(l, category.getFolderTableName(), tenantItemFolder.getTableName());//查询项目下的卷
                if(!(folderIdsByItemIds== null || folderIdsByItemIds.length==0)){
                    for(int j=0;j<folderIdsByItemIds.length;j++){
                        Long folderIdsByItemId = folderIdsByItemIds[j];
                        //Long[] l2 = {folderIdsByItemId};
                        //Long[] daIdsByFolderIds = yqdaMapper.getDaIdsByFolderIds(l2, category.getFileTableName(), tenantYqdaFolder.getTableName());//查询卷下的件
                        //if(!(daIdsByFolderIds== null || daIdsByFolderIds.length==0)){
                            idsStr.add(String.valueOf(folderIdsByItemId));
                        //}

                    }
                }
            }
            if("V".equals(daType)){
                Long[] daIdsByFolderIds = yqdaMapper.getDaIdsByFolderIds(l, category.getFileTableName(), tenantYqdaFolder.getTableName());//查询卷下的件
                if(!(daIdsByFolderIds== null || daIdsByFolderIds.length==0)){
                    for(int i1 = 0;i1<daIdsByFolderIds.length;i1++){
                        idsStr.add(String.valueOf(daIdsByFolderIds[i1]));
                    }
                }
            }
            if(idsStr.size()!=0){
                map.put(id,idsStr);
            }
        }
        return map;
    }

    private String getDictVal(String fieldName,Object dict){

        String DictVal = "";
        List<TenantSysDictData> list = sysDictTypeService.selectDictDataByType(fieldName);
        if(list!=null && list.size()>0){
            if(dict!=null) {
                for (TenantSysDictData dictData : list) {
                    if (dict.equals(dictData.getDictValue())) {
                        DictVal = dictData.getDictLabel();
                        break;
                    }
                }
            }
        }else {
            DictVal = getNull(dict);
        }
        return DictVal;
    }
    private String getNull(Object val){
        if(val == null){
            return "";
        }else {
            return String.valueOf(val);
        }
    }
}
